<template>
	<view class="profile-page">
		<!-- 页面标题和右上角控制 -->
		<!-- <view class="header">
			<view class="title-section">
				<text class="title-text">我的</text>
				<view class="top-controls">
					<text class="control-icon">⋯</text>
					<text class="control-separator">|</text>
					<text class="control-icon">─</text>
					<text class="control-separator">|</text>
					<text class="control-icon">◎</text>
				</view>
			</view>
		</view> -->

		<!-- 用户信息区域 -->
		<view class="user-info-section">
			<view class="user-info">
				<image class="avatar" :src="userAvatar" mode="aspectFill" />
				<view class="user-details" @click="handleUserDetailsClick">
					<view class="nickname-section">
						<text class="nickname">{{ userNickname }}</text>
					</view>
					<view class="id-section">
						<text class="user-id">{{ userId }}</text>
					</view>
				</view>
				<view class="edit-icon" @click="handleEdit">📝</view>
			</view>
			<!-- 注册账号按钮 - 未登录时显示 -->
			<view v-if="!isLoggedIn" class="register-section">
				<button class="register-btn" @click="goToRegister">注册账号</button>
			</view>
		</view>

		<!-- 统计数据 -->
		<view class="stats-section">
			<view class="stats-row">
				<view class="stat-item">
					<text class="stat-value">{{ stats[0].value }}</text>
					<text class="stat-label">{{ stats[0].label }}</text>
				</view>
				<view class="stat-item">
					<text class="stat-value">{{ stats[1].value }}</text>
					<text class="stat-label">{{ stats[1].label }}</text>
				</view>
				<view class="stat-item">
					<text class="stat-value">{{ stats[2].value }}</text>
					<text class="stat-label">{{ stats[2].label }}</text>
				</view>
				<view class="stat-item">
					<text class="stat-value">{{ stats[3].value }}</text>
					<text class="stat-label">{{ stats[3].label }}</text>
				</view>
			</view>
		</view>

		<!-- 跑腿达人卡片 -->
		<view class="runner-card">
			<view class="title">跑腿达人</view>
			<sar-button size="small" type="mild" @click="verifyRunner">立即认证</sar-button>
		</view>

		<!-- 常用工具 -->
		<view class="section">
			<view class="section-title">常用工具</view>
			<view class="grid-container">
				<view class="grid-item" @click="nav('publish')">
					<view class="icon-wrapper">
						<text class="icon">📄</text>
					</view>
					<text class="label">我的发布</text>
				</view>
				<view class="grid-item" @click="nav('likes')">
					<view class="icon-wrapper">
						<text class="icon">❤️</text>
					</view>
					<text class="label">我的喜欢</text>
				</view>
				<view class="grid-item" @click="nav('reward')">
					<view class="icon-wrapper">
						<text class="icon">💬</text>
					</view>
					<text class="label">我的打赏</text>
				</view>
				<view class="grid-item" @click="nav('address')">
					<view class="icon-wrapper">
						<text class="icon">📍</text>
					</view>
					<text class="label">我的地址</text>
				</view>
			</view>
		</view>

		<!-- 我的服务 -->
		<view class="section">
			<view class="section-title">我的服务</view>
			<view class="grid-container">
				<view class="grid-item" @click="nav('vip')">
					<view class="icon-wrapper">
						<text class="icon">⭐</text>
					</view>
					<text class="label">VIP会员</text>
				</view>
				<view class="grid-item" @click="nav('promote')">
					<view class="icon-wrapper">
						<text class="icon">📦</text>
					</view>
					<text class="label">我的推广</text>
				</view>
				<view class="grid-item" @click="nav('coupon')">
					<view class="icon-wrapper">
						<text class="icon">🎁</text>
					</view>
					<text class="label">商家优惠券</text>
				</view>
				<view class="grid-item" @click="nav('service')">
					<view class="icon-wrapper">
						<text class="icon">📞</text>
					</view>
					<text class="label">联系客服</text>
				</view>
				<view class="grid-item" @click="nav('ticket')">
					<view class="icon-wrapper">
						<text class="icon">🎫</text>
					</view>
					<text class="label">平台券</text>
				</view>
				<view class="grid-item" @click="nav('notify')">
					<view class="icon-wrapper">
						<text class="icon">🔔</text>
					</view>
					<text class="label">消息订阅</text>
				</view>
				<view class="grid-item" @click="nav('setting')">
					<view class="icon-wrapper">
						<text class="icon">⚙️</text>
					</view>
					<text class="label">设置管理</text>
				</view>
				<view class="grid-item" @click="goToLogin">
					<view class="icon-wrapper">
						<text class="icon">🔐</text>
					</view>
					<text class="label">返回登录</text>
				</view>
			</view>
		</view>

		
	</view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, nextTick, watch } from 'vue'
import { useUserStore } from '@/stores'

const userStore = useUserStore()

// 用户ID - 不显示任何内容
const userId = computed(() => {
	return ''
})

// 是否已登录与展示名称
const isLoggedIn = computed(() => {
	// 检查是否有用户信息
	const hasUserInfo = !!userStore.userInfo
	// 检查token是否有效（如果有token的话）
	const hasValidToken = userStore.accessToken ? !userStore.isAccessTokenExpired() : true
	// 对于QQ登录等第三方登录，只要有用户信息就认为是已登录
	return hasUserInfo && (hasValidToken || !userStore.accessToken)
})

// 检查登录状态并处理
const checkLoginStatus = () => {
	if (!isLoggedIn.value) {
		// 如果未登录，直接跳转到登录页面，不显示任何提示
		uni.navigateTo({ 
			url: '/pages/my/login/login',
			fail: (err) => {
				// 如果跳转失败，尝试使用reLaunch
				uni.reLaunch({ url: '/pages/my/login/login' })
			}
		})
		return false
	}
	return true
}

// 响应式头像数据
const currentAvatar = ref(uni.getStorageSync('userAvatar') || '/app/icons/120x120.png')

// 计算属性：获取用户头像
const userAvatar = computed(() => {
	// 优先使用store中的头像，其次使用本地存储的头像，最后使用默认头像
	return userStore.userInfo?.avatar || currentAvatar.value
})

// 计算属性：获取用户昵称
const userNickname = computed(() => {
	if (isLoggedIn.value) {
		// 显示昵称，不显示用户ID
		return userStore.userInfo?.nickName || '用户'
	} else {
		return '未登录'
	}
})

// 更新头像的函数
const updateAvatar = () => {
	const storedAvatar = uni.getStorageSync('userAvatar')
	
	if (storedAvatar && storedAvatar !== currentAvatar.value) {
		// 检查是否是有效的头像URL，但允许temp://格式
		if (storedAvatar.startsWith('blob:')) {
			return
		}
		
		currentAvatar.value = storedAvatar
		
		// 更新store中的头像
		if (userStore.userInfo) {
			userStore.setUserInfo({
				...userStore.userInfo,
				avatar: storedAvatar
			})
		}
	}
}

// 测试存储函数
const testStorage = () => {
	// 模拟头像更新
	const testAvatar = 'https://example.com/test-avatar.jpg'
	uni.setStorageSync('userAvatar', testAvatar)
	
	// 延迟更新
	setTimeout(() => {
		updateAvatar()
	}, 100)
}

// 调试头像状态
const debugAvatarStatus = () => {
	// 静默调试，不输出日志
}

// 强制刷新头像
const forceRefreshAvatar = () => {
	const storedAvatar = uni.getStorageSync('userAvatar')
	
	if (storedAvatar) {
		currentAvatar.value = storedAvatar
	}
}

// 页面显示时的处理
const onShow = () => {
	updateAvatar()
}

// 监听头像更新事件
onMounted(() => {
	// 监听头像更新事件
	uni.$on('avatarUpdated', (newAvatar: string) => {
		currentAvatar.value = newAvatar
	})
	
	// 监听页面显示事件
	uni.$on('pageShow', () => {
		onShow()
	})
	
	// 监听用户信息更新事件
	uni.$on('userInfoUpdated', () => {
		// 静默处理用户信息更新
	})
	
	// 初始更新头像
	updateAvatar()
})

// 暴露onShow给页面使用
defineExpose({
	onShow
})

// 页面卸载时清理事件监听器和定时器
onUnmounted(() => {
	uni.$off('avatarUpdated')
	uni.$off('pageShow')
	// 定时器会在各自的函数中清理
})

const stats = ref([
	{ label: '余额', value: '0.00' },
	{ label: '关注', value: '0' },
	{ label: '粉丝', value: '0' },
	{ label: '圈子', value: '0' }
])

const verifyRunner = () => {
	uni.$tao?.toast?.('去认证流程（示例）')
}

const nav = (name: string) => {
	uni.$tao?.toast?.('点击：' + name)
}

const goBack = () => {
	uni.switchTab({ url: '/pages/my/my' }) 
}

// 处理编辑按钮点击
const handleEdit = () => {
	// 检查登录状态，如果未登录则跳转到登录页面
	if (checkLoginStatus()) {
		// 已登录，跳转到个人资料页面
		uni.navigateTo({ 
			url: '/pages/my/profile/profile',
			fail: (err) => {
				uni.$tao?.toast?.('页面跳转失败')
			}
		})
	}
}

// 处理用户详情区域点击
const handleUserDetailsClick = () => {
	if (!isLoggedIn.value) {
		// 未登录，跳转到登录页面
		uni.navigateTo({ 
			url: '/pages/my/login/login',
			fail: (err) => {
				uni.$tao?.toast?.('页面跳转失败')
			}
		})
	} else {
		// 已登录，显示退出登录确认对话框
		uni.showModal({
			title: '退出登录',
			content: '确定要退出当前账号吗？',
			confirmText: '退出',
			cancelText: '取消',
			success: (res) => {
				if (res.confirm) {
					// 用户确认退出
					userStore.logout()
					uni.$tao?.toast?.('已退出登录')
				}
			}
		})
	}
}

// 跳转到注册账号页面
const goToRegister = () => {
	uni.navigateTo({ 
		url: '/pages/my/register/register',
		fail: (err) => {
			uni.$tao?.toast?.('页面跳转失败')
		}
	})
}

// 跳转到登录页面
const goToLogin = () => {
	uni.navigateTo({ 
		url: '/pages/my/login/login',
		fail: (err) => {
			uni.$tao?.toast?.('页面跳转失败')
		}
	})
}
</script>

<style lang="scss" scoped>
.profile-page {
	min-height: 100vh;
	background-color: rgb(255, 110, 38);
	position: relative;
	overflow-y: auto;
	overflow-x: hidden;
}

// 头部区域
.header {
	padding: 40rpx 30rpx 20rpx 30rpx;
}

.title-section {
	display: flex;
	align-items: center;
	justify-content: center;
	position: relative;
}

.title-text {
	font-size: 48rpx;
	font-weight: bold;
	color: #fff;
}

.top-controls {
	position: absolute;
	right: 0;
	top: 50%;
	transform: translateY(-50%);
	display: flex;
	align-items: center;
	background: rgba(255, 255, 255, 0.2);
	border-radius: 20rpx;
	padding: 10rpx 20rpx;
}

.control-icon {
	font-size: 24rpx;
	color: #fff;
	margin: 0 5rpx;
}

.control-separator {
	font-size: 20rpx;
	color: rgba(255, 255, 255, 0.6);
	margin: 0 5rpx;
}

// 用户信息区域
.user-info-section {
	padding: 0 30rpx 30rpx 30rpx;
}

.user-info {
	display: flex;
	align-items: center;
	justify-content: space-between;
}

.avatar {
	width: 120rpx;
	height: 120rpx;
	border-radius: 60rpx;
	background: #fff;
	border: 4rpx solid rgba(255, 255, 255, 0.3);
}

.user-details {
	flex: 1;
	margin-left: 30rpx;
	cursor: pointer;
	transition: opacity 0.2s ease;
}

.user-details:active {
	opacity: 0.8;
}

.nickname-section {
	margin-bottom: 10rpx;
}

.nickname {
	font-size: 36rpx;
	color: #fff;
	font-weight: bold;
}

.id-section {
	display: flex;
	align-items: center;
}

.user-id {
	font-size: 32rpx;
	color: #fff;
	font-weight: 500;
}

.edit-icon {
	font-size: 36rpx;
	color: #fff;
	cursor: pointer;
	padding: 10rpx;
	border-radius: 50%;
	background: rgba(255, 255, 255, 0.2);
	transition: all 0.2s ease;
}

.edit-icon:active {
	background: rgba(255, 255, 255, 0.3);
	transform: scale(0.95);
}

// 注册账号区域
.register-section {
	margin-top: 20rpx;
	text-align: center;
}

.register-btn {
	width: 100%;
	height: 80rpx;
	background: rgba(255, 255, 255, 0.2);
	color: #fff;
	font-size: 28rpx;
	font-weight: 500;
	border: 2rpx solid rgba(255, 255, 255, 0.3);
	border-radius: 40rpx;
	transition: all 0.2s ease;
}

.register-btn:active {
	background: rgba(255, 255, 255, 0.3);
	transform: scale(0.98);
}

// 统计数据区域
.stats-section {
	padding: 0 30rpx 40rpx 30rpx;
}

.stats-row {
	display: flex;
	justify-content: space-between;
	background: rgba(255, 255, 255, 0.1);
	border-radius: 20rpx;
	padding: 30rpx 20rpx;
}

.stat-item {
	display: flex;
	flex-direction: column;
	align-items: center;
	flex: 1;
}

.stat-value {
	font-size: 36rpx;
	font-weight: bold;
	color: #fff;
	margin-bottom: 10rpx;
}

.stat-label {
	font-size: 24rpx;
	color: rgba(255, 255, 255, 0.8);
}

// 其他内容区域
.runner-card {
	margin: 30rpx;
	padding: 30rpx;
	background: #fff;
	border-radius: 20rpx;
	display: flex;
	align-items: center;
	justify-content: space-between;
}

.runner-card .title {
	font-size: 32rpx;
	font-weight: bold;
	color: #333;
}

.section {
	margin: 30rpx;
	padding: 30rpx;
	background: #fff;
	border-radius: 20rpx;
}

.section-title {
	font-size: 32rpx;
	font-weight: bold;
	color: #333;
	margin-bottom: 30rpx;
}

.grid-container {
	display: grid;
	grid-template-columns: repeat(4, 1fr);
	gap: 30rpx;
}

.grid-item {
	display: flex;
	flex-direction: column;
	align-items: center;
	cursor: pointer;
	transition: transform 0.2s ease;
}

.grid-item:active {
	transform: scale(0.95);
}

.icon-wrapper {
	width: 80rpx;
	height: 80rpx;
	background: #f8f9fa;
	border-radius: 20rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	margin-bottom: 15rpx;
}

.icon {
	font-size: 36rpx;
}

.label {
	font-size: 24rpx;
	color: #666;
	text-align: center;
}

.footer-actions {
	margin: 30rpx;
}
</style>
  
  
  
